package com.newland.zxy.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @author : zhangxuyuan
 * @Project: springcloudoauth2
 * @Package com.newland.zxy.config
 * @date Date : 2021年02月05日 9:23
 *
 * Oauth2相关配置
 */
@Configuration
public class OauthConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private MyAccessTokenConverter myAccessTokenConverter;

    private String key="imzxy";


    /**
     * 暴露外部访问接口，如获取token的接口，检查token的接口
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
        //允许客户端表单认证
        security.allowFormAuthenticationForClients()
                //放行获取token接口
                .tokenKeyAccess("permitAll()")
                //放行token检查接口
                .checkTokenAccess("permitAll()");
    }


    /**
     * 客户端详情配置，配置资源服务器相关参数
     * @param clients
     * @throws Exception
     */

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
        clients.inMemory()
                //设置clien_id
                .withClient("testClient")
                //设置允许访问的资源id
                .resourceIds("test")
                //设置secret_id
                .secret("111")
                //设置授权类型
                .authorizedGrantTypes("password","refresh_token")
                //可访问区域
                .scopes("all")
                .accessTokenValiditySeconds(600)
                .refreshTokenValiditySeconds(3600);
    }

    /**
     * 认证服务器是玩转token的，那么这里配置token令牌管理相关（token此时就是一个字符串，当下的token需要在服务器端存储，
     * 那么存储在哪里呢？都是在这里配置）
     * @param endpoints
     * @throws Exception
     */

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
        endpoints.authenticationManager(manager)
                .tokenServices(this.tokenServices())
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
    }

    public AuthorizationServerTokenServices tokenServices()
    {
        DefaultTokenServices tokenServices=new DefaultTokenServices();

        tokenServices.setSupportRefreshToken(true);

        tokenServices.setTokenStore(new JwtTokenStore(converter()));

        tokenServices.setTokenEnhancer(converter());
        //token有效时间10分钟
        tokenServices.setAccessTokenValiditySeconds(600);
        //token刷新有效时间，1小时
        tokenServices.setRefreshTokenValiditySeconds(259200);
        return tokenServices;
    }


    public JwtAccessTokenConverter converter()
    {
        JwtAccessTokenConverter tokenConverter=new JwtAccessTokenConverter();
        tokenConverter.setSigningKey(this.key);
        tokenConverter.setVerifier(new MacSigner(key));
        tokenConverter.setAccessTokenConverter(myAccessTokenConverter);
        return tokenConverter;
    }
}
